package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.UserMapper;
import cn.tedu.coolshark.pojo.dto.UserDTO;
import cn.tedu.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserDTO user, HttpServletResponse response, HttpSession session){
        System.out.println("user = " + user);
        UserVO u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            if(user.getPassword().equals(u.getPassword())){
                //往Session对象中保存登录用户的信息
                session.setAttribute("user",u);
                //判断是否需要记住用户名和密码
                if (user.getRem()){
                    //创建Cookie对象 把用户名和面装进Cookie
                    Cookie c1 = new Cookie("username",user.getUsername());
                    //设置保存时长 单位秒
                    c1.setMaxAge(60*60*24*30);
                    Cookie c2 = new Cookie("password",user.getPassword());
                    //把创建好的Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }

                return 1;//登录成功!
            }return 3;
        }
        return 2;//用户名不存在!

    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){//从session里获取
        return (UserVO) session.getAttribute("user");

    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");//删除session里面的数据
    }//工程重启时session里面的数据就没有了
}
